import React from 'react'
import { connect } from 'mirrorx'
import ControlItem from './control-item'

class App extends React.Component {
  constructor (props) {
    super(props)

    this.state = {
      toSlefMap: {}
    }
  }

  componentWillReceiveProps (nextProps) {
    if (nextProps.initValueArr !== this.props.initValueArr) {
      this.setInitDataList(nextProps.initValueArr)
    }
  }

  setInitDataList (initValueArr) {
    if (!initValueArr || (initValueArr && initValueArr.length === 0)) {
      return
    }
    this.tempLen = initValueArr.length
    let toSlefMap = this.state.toSlefMap
    let type = this.props.type

    initValueArr.forEach((item, index) => {
      if (type === 2 && item.relationWithHolders === '1') {
        toSlefMap[index + 1] = true
      }
    })

    this.setState({toSlefMap})
  }

  componentDidMount () {

  }

  // 获取各个模块的填写项
  getRowsDom (data, blockItem, itemIndex) {
    const {type, blocksMap = {}, step, sid = 0} = this.props
    const {toSlefMap} = this.state
    let policyholderItems = blocksMap[1] || []

    let fieldkeys = T.pluck(policyholderItems, 'customizeCode')
    let noRenderKeys = ['certiFaceUrl', 'certibackUrl', 'insuredPersonNumber', 'enterpriseCertificateType']

    data = data.filter((item) => {
      let isSelf = (type === 2 || type === 3) && toSlefMap[blockItem.id] && fieldkeys.indexOf(item.customizeCode) > -1
      let isNoRender = noRenderKeys.indexOf(item.customizeCode) > -1
      return !(isSelf || isNoRender)
    })

    let rightContent
    let rowsDom = data.map((item, index) => {
      rightContent = null
      let keycode = item.customizeCode
      if (keycode === 'benefitRatio') {
        rightContent = <span className='block-right-content'>%</span>
      }
      const fieldKey = keycode + '_' + type + '_' + blockItem.id + '_' + sid
      const isDisabled = step !== 1
      item.fieldKey = fieldKey
      item.disabled = isDisabled
      item.value = blockItem.values && blockItem.values[keycode]
      const { getFieldProps } = this.props.form

      if (keycode === 'relationWithHolders') {
        let flag = this.isInsurantToSelf()

        if (flag && flag !== fieldKey) {
          item.flist = item.items.filter((fitem) => {
            return fitem.id !== '1'
          })
        } else {
          item.flist = null
        }
      }

      let bottomClass = index === data.length - 1 ? '' : 'bor-bottom'
      return (
        <div className={'control-item ' + bottomClass} key={fieldKey}>
          <ControlItem
            type={type}
            form={this.props.form}
            item={item}
            getFieldProps={getFieldProps}
            onChangeCallback={(value) => this.valueChangeAction(fieldKey, value, blockItem, itemIndex)}
          />

          {rightContent}
        </div>)
    })

    return rowsDom
  }

  // 判断受保人中有没有关系为本人
  isInsurantToSelf () {
    const {getFieldsValue} = this.props.form
    let results = getFieldsValue()

    let flag = false
    for (let key in results) {
      if (key.indexOf('relationWithHolders_2') === 0 && results[key] && results[key][0] === '1') {
        console.log('有为本人投保')
        flag = key
        break
      }
    }

    return flag
  }

  // 表单发生变化
  valueChangeAction (fieldKey, value, blockItem, itemIndex) {
    if (value instanceof Date) {
      value = T.formatDate('yyyy-MM-dd', value) + ' 00:00:00'
    }

    if (fieldKey.indexOf('relationWithHolders_') === 0) {
      this.relationShipChange(value, blockItem.id)
    }

    this.changePrice(fieldKey.split('_')[0], value)

    console.log('Change:', fieldKey, value)
  }

  // 价格试算
  changePrice (key, value) {
    let {type, trialPrice} = this.props
    let isTrial = type === 2 || (type === 1 && this.isInsurantToSelf())

    if (!isTrial) {
      return
    }

    trialPrice && trialPrice(key, value)
  }

  // 关系变化
  relationShipChange (value, blockItemId) {
    let toSlefMap = this.state.toSlefMap || {}
    toSlefMap[blockItemId] = value === '1'
    this.setState({toSlefMap}, () => {
      this.relationChnagePrice(toSlefMap[blockItemId])
    })
  }

  relationChnagePrice (isSelf) {
    const {getFieldsValue} = this.props.form
    let {trialPrice} = this.props
    let results = getFieldsValue()
    let obj = {}
    for (let key in results) {
      let arr = key.split('_')
      let keycode = arr[0]
      let type = arr[1]
      if (results[key] instanceof Date) {
        results[key] = T.formatDate('yyyy-MM-dd', results[key]) + ' 00:00:00'
      }
      if (isSelf) {
        if (type === '1') {
          obj[keycode] = results[key]
        }
      } else {
        if (type === '2') {
          obj[keycode] = results[key]
        }
      }
    }
    trialPrice && trialPrice(obj)
  }

  render () {
    const {type, itemIndex, blockItem, blocksMap = {}} = this.props
    const blockData = blocksMap[type] || []
    if (blockData.length === 0) {
      return null
    }

    return (
      <div key={itemIndex} className='fill-out'>
        {this.getRowsDom(blockData, blockItem, itemIndex)}
      </div>
    )
  }
}

export default connect(state => {
  return {
    blocksMap: state.insureModel.blocksMap
  }
})(App)
